﻿using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 分拣入库任务 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_PickInStockTaskController : ControllerBase
    {
        private readonly ILes_PickInStockTaskServices _Les_PickInStockTaskServices;
        private readonly IUser _user;
        private readonly IV_Les_PickInStockTaskServices _V_Les_PickInStockTaskServices;
        private readonly ILes_PersonHandlerRecordServices _les_PersonHandlerRecordServices;
        private readonly ILogger<Les_PickInStockTaskController> _logger;
        private readonly ILes_ProcedureRoleServices _les_ProcedureRoleServices;
        private readonly IUserRoleServices _userRoleServices;

        public Les_PickInStockTaskController(
             IUserRoleServices userRoleServices,
             ILes_ProcedureRoleServices les_ProcedureRoleServices,
            ILogger<Les_PickInStockTaskController> logger,
            IV_Les_PickInStockTaskServices V_Les_PickInStockTaskServices,
               ILes_PersonHandlerRecordServices les_PersonHandlerRecordServices,
            ILes_PickInStockTaskServices Les_PickInStockTaskServices, IUser user)
        {
            this._userRoleServices = userRoleServices;
            this._les_ProcedureRoleServices = les_ProcedureRoleServices;
            this._les_PersonHandlerRecordServices = les_PersonHandlerRecordServices;
            _Les_PickInStockTaskServices = Les_PickInStockTaskServices;
            _user = user;
            _V_Les_PickInStockTaskServices = V_Les_PickInStockTaskServices;
            this._logger = logger;
        }

        /// <summary> 
        /// 分页获取分拣入库任务列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<V_Les_PickInStockTask>>> Get([FromBody] V_Les_PickInStockTaskParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<V_Les_PickInStockTask, V_Les_PickInStockTaskParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<V_Les_PickInStockTask>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }

            #region 根据是否管理员进行过滤

            bool isManagerRole = await LesApiCommon.IsManagerRole(_userRoleServices, _user);
            if (isManagerRole == false)
            {
                Expression<Func<V_Les_PickInStockTask, bool>> whereExpression2 = a => a.CreateId == _user.ID;
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #endregion

            var data = await _V_Les_PickInStockTaskServices.QueryPage(whereConditions.data, param.page, param.pageSize, " CreateTime desc ");
            return new MessageModel<PageModel<V_Les_PickInStockTask>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };

        }

        /// <summary> 
        /// 获取单个分拣入库任务 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_PickInStockTask>> Get(int id = 0)
        {
            return new MessageModel<Les_PickInStockTask>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_PickInStockTaskServices.QueryById(id)
            };
        }


        /// <summary> 
        /// 删除分拣入库任务 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _Les_PickInStockTaskServices.QueryById(id);
                if (detail != null)
                {
                    data.success = await _Les_PickInStockTaskServices.DeleteById(detail.Id);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }
            else
            {
                data.success = false;
                data.msg = "删除失败,该分拣入库任务不存在";
            }
            return data;
        }

        /// <summary> 
        /// 逻辑删除分拣入库任务 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> LogicDelete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _Les_PickInStockTaskServices.QueryById(id);
                if (detail != null)
                {
                    detail.ModifyTime = DateTime.Now;
                    detail.ModifyBy = _user.Name;
                    detail.ModifyId = _user.ID;
                    //detail.IsDeleted = true; 
                    detail.OperationRemark = "删除";
                    data.success = await _Les_PickInStockTaskServices.Update(detail);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }
            else
            {
                data.success = false;
                data.msg = "删除失败,该分拣入库任务不存在";
            }
            return data;
        }



        /// <summary>
        /// 更新分拣入库任务是否分拣完成
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<bool>> UpdateIsPickFinish([FromBody] Les_PickInStockTask request)
        {
            var data = new MessageModel<bool>();
            try
            {
                if (!string.IsNullOrEmpty(request.Id))
                {
                    var detail = await _Les_PickInStockTaskServices.QueryById(request.Id);
                    if (detail != null)
                    {
                        data = await _Les_PickInStockTaskServices.UpdateIsPickFinishByBurdenWorkNo(request.IsPickFinish, detail, _user, false);

                        if (data.success)
                        {
                            data.msg = "更新是否分拣完成成功";

                            //保存人工处理日志
                            await _les_PersonHandlerRecordServices.SavePersonHandlerRecord(_user, "更新分拣入库任务是否分拣完成", detail.OperationRemark,
                                "表 Les_PickInStockTask，id:" + request.Id + ",更新IsPickFinish：" + request.IsPickFinish, request.MaterialName, request.BurdenWorkNo);
                        }
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "更新分拣入库任务是否分拣完成失败，数据不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新分拣入库任务是否分拣完成出现异常:" + ex.Message);
                return MessageModel<bool>.Fail("更新分拣入库任务是否分拣完成出现异常:" + ex.Message);
            }
        }
    }
}
